<template>
  <div>
    <el-form label-position="left" label-width="100px" style="width:100%;">
      <el-form-item label="菜单名称："><el-input v-model="formData.menuName" placeholder="请输入菜单名称" class="filter-item" /></el-form-item>
      <el-form-item label="菜单路径："><el-input v-model="formData.path" placeholder="请输入菜单路径" class="filter-item" /></el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button icon="el-icon-close" @click="cancel">取消</el-button>
      <el-button v-waves :loading="confirmLoading" type="primary" icon="el-icon-check" @click="submit">确定</el-button>
    </div>
  </div>
</template>
<script>
import { getSysMenuDetail, addSysMenu, editSysMenu } from '@/api/menu';
import waves from '@/directive/waves';

export default {
  name: 'SysMenuAdd',
  directives: { waves },
  props: {
    id: {
      type: Number,
      default: null
    },
    pid: {
      type: Number,
      default: null
    },
    length: {
      type: Number,
      default: null
    },
    pidMenuName: {
      type: String,
      default: ''
    },
    pidTotal: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      confirmLoading: false,
      formData: {
      }
    };
  },
  created() {
    if (this.id) {
      this.getDetail(this.id);
    }
  },
  methods: {
    async getDetail(id) {
      await getSysMenuDetail(id).then(response => {
        this.formData = response.data;
      });
    },
    async submit() {
      if (this.formData.menuName === '') {
        this.$message.error('请输入菜单名称');
        return;
      }
      if (this.formData.path === '') {
        this.$message.error('请输入菜单路径');
        return;
      }
      this.confirmLoading = true;
      if (this.id) {
        await editSysMenu(this.formData).then(res => {
          this.confirmLoading = false;
          if (res.msg !== 'OK') {
            this.$message.error(res.msg);
            return;
          }
          this.$message.success('编辑成功');
          this.$emit('cancelClose', true, 'edit', null);
        });
      } else {
        if (this.pid !== null) {
          this.formData.pid = this.pid;
          this.formData.rank = this.pidTotal + 1;
        } else {
          this.formData.rank = this.length + 1;
          this.formData.pid = 0;
        }
        await addSysMenu(this.formData).then(res => {
          this.confirmLoading = false;
          if (res.msg !== 'OK') {
            this.$message.error(res.msg);
            return;
          }
          this.$message.success('新增成功');
          this.$emit('cancelClose', true, 'add', this.pid);
        });
      }
    },
    cancel() {
      if (this.id) {
        this.$emit('cancelClose', false, 'edit', null);
      } else {
        this.$emit('cancelClose', false, 'add', this.pid);
      }
    }
  }
};
</script>
